import axios from 'axios';
import type { AxiosResponse, InternalAxiosRequestConfig } from 'axios';

import { sm4 } from 'sm-crypto';

// 假设这是通过密钥协商获取到的 SM4 密钥
const sm4Key = '0123456789abcdef0123456789abcdef';

// 加密请求数据
const encryptRequestData = (data: any) => {
    if (typeof data === 'object') {
        const jsonData = JSON.stringify(data);
        return sm4.encrypt(jsonData, sm4Key, { mode: 'cbc', iv: '0000000000000000' });
    }
    return data;
};

// 解密响应数据
const decryptResponseData = (data: string) => {
    const decryptedData = sm4.decrypt(data, sm4Key, { mode: 'cbc', iv: '0000000000000000' });
    return JSON.parse(decryptedData);
};

// 创建 Axios 实例
const service = axios.create({
    baseURL: '/api', // 根据实际情况修改
    timeout: 5000,
});

// 请求拦截器
service.interceptors.request.use(
    (config: InternalAxiosRequestConfig ) => {
        if (config.data) {
            config.data = encryptRequestData(config.data);
        }
        return config;
    },
    (error) => {
        console.error('请求拦截器错误:', error);
        return Promise.reject(error);
    }
);

// 响应拦截器
service.interceptors.response.use(
    (response: AxiosResponse) => {
        if (typeof response.data === 'string') {
            response.data = decryptResponseData(response.data);
        }
        return response;
    },
    (error) => {
        console.error('响应拦截器错误:', error);
        return Promise.reject(error);
    }
);

export default service;